package com.tungse.juc;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;

/**
 * 减法 计数器
 */
public class CountDownLatch_Demo {
    public static void main(String[] args) throws InterruptedException {
        //总数6//倒计时器
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"离开教室");
                countDownLatch.countDown();//总数减一
            }, String.valueOf(i)).start();
        }

        countDownLatch.await();//等待计数器归零, 然后执行后续逻辑
        System.out.println("教室没人了，锁门");

    }


    @Test
    public void test() throws InterruptedException {
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch endLatch = new CountDownLatch(10);
        System.out.println("比赛开始");
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    startLatch.await(); // 等待起跑信号
                    System.out.println(Thread.currentThread().getName() + "开始跑步");
                    endLatch.countDown();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
        Thread.sleep(2000);
        startLatch.countDown(); // 同时释放所有线程
        endLatch.await();       // 等待所有线程结束
    }
}
